package com.example.havi.ui.voiceRecorder;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import androidx.annotation.AttrRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.havi.R;
import com.example.havi.helper.ChatHelper;
import com.hyphenate.EMError;

/**
 * Created by Frank on 2017/4/25.
 * 仿qq 录音控件
 */

public class RecorderVoiceView extends FrameLayout {

    private ImageView recorderButtonIv;
    private ImageView recorderDeleteIv;
    private TextView status_tv;
    private TextView tv_line;
    private int recorderButtonWidth;
    private int recorderButtonHeight;
    private int deleteButtonwidth;
    private int deleteButtonHeight;
    private int singleTouchOutRangeHeight;
    private int lineWidth;
    private float dx;
    private float dy;
    private float mx;
    private float my;
    private boolean isDeleteRecorder;   //是否可以删除
    private float mxv;
    private float mxy;
    private EaseVoiceRecorder voiceRecorder;

    public RecorderVoiceView(@NonNull Context context) {
        this(context,null);
    }

    public RecorderVoiceView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public RecorderVoiceView(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }

    protected Handler micImageHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            // 切换msg切换图片 录音过程声音大小显示的图片
        }
    };

    private void initView() {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.voice_recorder,null);
        recorderButtonIv = (ImageView) view.findViewById(R.id.recorderButtonIv);
        recorderDeleteIv = (ImageView) view.findViewById(R.id.recorderDeleteIv);
        tv_line = (TextView) view.findViewById(R.id.tv_line);
        status_tv = (TextView) view.findViewById(R.id.status_tv);
        setTouchListener();
        addView(view);
        voiceRecorder = new EaseVoiceRecorder(micImageHandler);
    }

    @SuppressLint("ClickableViewAccessibility")
    private void setTouchListener() {
        recorderButtonIv.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:
//                        Log.e("frank","触摸按下 X="+event.getX()+"  Y="+event.getY());
                        recorderButtonWidth = recorderButtonIv.getWidth();
                        recorderButtonHeight = recorderButtonIv.getHeight();
                        deleteButtonwidth = recorderDeleteIv.getHeight();
                        deleteButtonHeight = recorderDeleteIv.getHeight();
                        singleTouchOutRangeHeight = (recorderButtonHeight- deleteButtonHeight)/2; //超出删除按钮高度的半值
                        lineWidth = tv_line.getWidth(); //线宽
                        dx = event.getX();  //按下时的 x坐标
                        dy = event.getY();  //按下时的y坐标
                        ScaleAnimation animation =new ScaleAnimation(1f, 1.1f, 1f, 1.1f,
                                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                        animation.setFillAfter(true);
                        animation.setDuration(200);//设置动画持续时间
                        animation.setAnimationListener(new Animation.AnimationListener() {
                            @Override
                            public void onAnimationStart(Animation animation) {

                            }

                            @Override
                            public void onAnimationEnd(Animation animation) {
                                ScaleAnimation animation1 =new ScaleAnimation(1.1f, 1.0f, 1.1f, 1.0f,
                                        Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                                animation1.setFillAfter(true);
                                animation1.setDuration(200);//设置动画持续时间
                                recorderButtonIv.setAnimation(animation1);
                                animation1.startNow();
                            }

                            @Override
                            public void onAnimationRepeat(Animation animation) {

                            }
                        });
                        recorderButtonIv.setAnimation(animation);
                        animation.startNow();
                        //开始录制语音
                        status_tv.setText("正在录音");
                        voiceRecorder.startRecording(ChatHelper.getInstance().getAppContext());
                        break;
                    case MotionEvent.ACTION_UP:
//                        Log.e("frank","触摸抬起 X="+event.getX()+"  Y="+event.getY());
                        if(isDeleteRecorder){
                            //删除语音录制 取消发送
                            discardRecording();
                        }else{
                            //发送语音
                            try {
                                int length = voiceRecorder.stopRecoding();
                                if (length > 0) {
                                    if (mVoiceRecorderCallback != null) {
                                        mVoiceRecorderCallback.onVoiceRecordComplete(voiceRecorder.getVoiceFilePath(), length);
                                    }
                                } else if (length == EMError.FILE_INVALID) {
                                    Toast.makeText(getContext(), "录音权被禁止", Toast.LENGTH_SHORT).show();
                                } else {
                                    Toast.makeText(getContext(), "录音时间太短", Toast.LENGTH_SHORT).show();
                                }
                            } catch (Exception e) {
                                Log.e("frank","发送语音jkjjjjj"+e.toString());
                                e.printStackTrace();
                                Toast.makeText(getContext(), "语音发送失败,请重试！", Toast.LENGTH_SHORT).show();
                            }
                        }
                        recorderDeleteIv.setImageResource(R.drawable.recorder_delete);
                        status_tv.setText("按住说话");
                        break;
                    case MotionEvent.ACTION_CANCEL:
//                        Log.e("frank","触摸取消 X="+event.getX()+"  Y="+event.getY());
                        break;
                    case MotionEvent.ACTION_MOVE:
//                        Log.e("frank","触摸移动 X="+event.getX()+"  Y="+event.getY());
                        mx = event.getX();  //移动时的 x坐标
                        my = event.getY();  //移动时的y坐标
                        mxv = mx-dx;    //x轴移动距离
                        mxy = my-dy;    //y轴移动距离
//                        Log.e("frank","参数：dx="+dx+" dy="+dy+" mx="+mx+" my="+my
//                                +" mxv="+mxv+" mxy="+mxy);
//                        Log.e("frank","参数：lineWidth="+lineWidth+" singleTouchOutRangeHeight"+singleTouchOutRangeHeight);
//                        Log.e("frank","参数：recorderButtonWidth="+recorderButtonWidth+" recorderButtonHeight"+recorderButtonHeight);
//                        Log.e("frank","参数：deleteButtonwidth="+deleteButtonwidth+" deleteButtonHeight"+deleteButtonHeight);
                        if(dy >0 && dy<singleTouchOutRangeHeight){
                            //y坐标 相对于录音按钮的顶部触摸范围（顶部触摸范围）
                            //触摸右移同时下移（顶部下移才会到删除按钮范围）
                            if(mx>dx && my>dy){
                                //x坐标移动距离满足录音按钮与删除按钮之间的范围 且y坐标不能超出删除按钮范围
                                if((mxv>recorderButtonWidth-dx+lineWidth)
                                        &&mxv<(recorderButtonWidth-dx+lineWidth+deleteButtonwidth)
                                        &&mxy>(singleTouchOutRangeHeight-dy)
                                        &&mxy<singleTouchOutRangeHeight-dy+deleteButtonHeight){
                                    isDeleteRecorder=true;
                                }else{
                                    isDeleteRecorder=false;
                                }
                            }else{
                                isDeleteRecorder=false;
                            }

                        }else if(dy >singleTouchOutRangeHeight && dy<singleTouchOutRangeHeight+ deleteButtonHeight){
                            //y坐标 相对于录音按钮与删除按钮等高的中间部分（中间触摸范围）
                            //触摸右移
                            if(mx>dx){
                                //x坐标移动距离满足录音按钮与删除按钮之间的范围 且y坐标不能超出删除按钮范围
                                if(mxv>(recorderButtonWidth-dx+lineWidth)
                                        &&mxv<(recorderButtonWidth-dx+lineWidth+deleteButtonwidth) ){
                                    if(dy>my){ //上移
                                        if(Math.abs(mxy)<dy-singleTouchOutRangeHeight){
                                            isDeleteRecorder=true;
                                        }else{
                                            isDeleteRecorder=false;
                                        }
                                    }else{ //下移
                                        if(mxy<recorderButtonHeight-singleTouchOutRangeHeight-dy){
                                            isDeleteRecorder=true;
                                        }else{
                                            isDeleteRecorder=false;
                                        }
                                    }

                                }else{
                                    isDeleteRecorder=false;
                                }
                            }else{
                                isDeleteRecorder=false;
                            }

                        }else if(dy >singleTouchOutRangeHeight+ deleteButtonHeight && dy<recorderButtonHeight){
                            //y坐标 相对于录音按钮的底部触摸范围（底部触摸范围）
                            //触摸右移同时上移（底部上移才会到删除按钮范围）
                            if(mx>dx && my<dy){
                                //x坐标移动距离满足录音按钮与删除按钮之间的范围 且y坐标不能超出删除按钮范围
                                if(mxv>(recorderButtonWidth-dx+lineWidth)
                                        &&mxv<(recorderButtonWidth-dx+lineWidth+deleteButtonwidth)
                                        && Math.abs(mxy)>(dy-singleTouchOutRangeHeight-deleteButtonHeight)
                                        && Math.abs(mxy)<(dy-singleTouchOutRangeHeight)){
                                    isDeleteRecorder=true;
                                }else{
                                    isDeleteRecorder=false;
                                }
                            }else{
                                isDeleteRecorder=false;
                            }
                        }

                        //更新ui显示是否可以删除录音
                        if(isDeleteRecorder){
                            recorderDeleteIv.setImageResource(R.drawable.recorder_delete_check);
                            status_tv.setText("松手删除录音");
                        }else{
                            recorderDeleteIv.setImageResource(R.drawable.recorder_delete);
                            status_tv.setText("正在录音");
                        }
                        requestLayout();
                        break;
                }
                return true;
            }
        });
    }


    public void discardRecording() {
        try {
            // 停止录音
            if (voiceRecorder.isRecording()) {
                voiceRecorder.discardRecording();
            }
        } catch (Exception e) {
            e.getStackTrace();
        }
    }


    public interface VoiceRecorderCallback {
        /**
         * 录音完毕
         *
         * @param voiceFilePath
         *            录音完毕后的文件路径
         * @param voiceTimeLength
         *            录音时长
         */
        void onVoiceRecordComplete(String voiceFilePath, int voiceTimeLength);
    }
    private VoiceRecorderCallback mVoiceRecorderCallback;
    public void setVoiceRecorderCallback(VoiceRecorderCallback callback){
        mVoiceRecorderCallback = callback;
    }




}
